using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;

/// <summary>
/// 回滚
/// </summary>
public class Rollback : IPlayer
{
    Queue<Frame> queframe = new Queue<Frame>();
    string filePath;
    int count;
    bool isPlaying;

    public void Init(string path)
    {
        filePath = path;
    }

    public void Play()
    {
        isPlaying = true;

        queframe.Clear();
        string jsonStr = File.ReadAllText(filePath);
        var listFrame = JsonConvert.DeserializeObject<List<Frame>>(jsonStr);
        int maxFrame = -1;
        for (int i = listFrame.Count - 1; i >= 0; i--)
        {   
            var frame = listFrame[i];
            if (maxFrame == -1)
            {
                maxFrame = frame.Id;
            }
            queframe.Enqueue(frame);
        }
        count = maxFrame;
        GameMgr.Instance.ResetVelocity();
    }

    public void Stop()
    {
        isPlaying = false;
        GameMgr.Instance.ResetVelocity();
    }

    public void Update()
    {
        if (!isPlaying)
            return;
        if (queframe.Count == 0)
            return;

        count--;

        //返回队列顶部元素
        var frame = queframe.Peek();
        //没有到达关键帧则返回
        if (frame.Id < count)
            return;

        GameMgr.Instance.Replay(frame);
        queframe.Dequeue();
    }
}
